package com.crazy.multids.config.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 此类的描述是：
 *
 * @author crazyhu@wezhuiyi.com
 * @date 2018-09-16 15:14
 **/
@Slf4j
@Configuration
@AutoConfigureAfter(MultipleDataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {

    @Autowired
    private AbstractRoutingDataSource routingDataSourceProxy;

    @Value("${mybatis.mapperLocations:classpath:mybatis/*.xml}")
    private String mapperLocations;

    @Value("${mybatis.mapperLocation:classpath:mybatis-config.xml}")
    private String configLocation;

    @Bean(name = "sqlSessionFactory")
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() throws Exception {

        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(routingDataSourceProxy);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources(mapperLocations));
        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-config.xml"));

//        Interceptor[] its = new Interceptor[2];
//        its[0] = new MybatisTimeoutInterceptor();
//        its[1] = new MybatisSQLPerformanceInterceptor();
//        sessionFactory.setPlugins(its);

        return sessionFactory.getObject();
    }
}
